package im

import (
	"fmt"
	"time"
	"strings"
	"errors"
	"dhfshop/models"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

// 商家模板配置表
type TemplateCfg struct {
	TemplateCfgId int64   `orm:"column(template_cfg_id);pk;auto" json:"template_cfg_id" form:"template_cfg_id"`
	PartnerId     int64   `orm:"column(partner_id);index" json:"partner_id" form:"partner_id"`
	AppId         string  `orm:"column(app_id);size(32)" json:"app_id" form:"app_id"`
	PubTitleId    string  `orm:"column(pub_title_id)" json:"pub_title_id" form:"pub_title_id"`          //公有模板标题ID
	PubTitle      string  `orm:"column(pub_title)" json:"pub_title" form:"pub_title"`                   //公有模板标题内容
	KeywordIdList string  `orm:"column(keyword_id_list)" json:"keyword_id_list" form:"keyword_id_list"` //公有模板关键词定制列表，以此来定制出需要的关键词
	TemplateId    string  `orm:"column(template_id)" json:"template_id" form:"template_id"`             //私有模板编号
	CreatedAt     time.Time   `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"` 
	CreatedAtStr  string      `orm:"-" json:"created_at,omitempty" form:"-"`
    UpdatedAt     time.Time   `orm:"auto_now;column(updated_at);type(datetime)" json:"-" form:"-"`         
	UpdatedAtStr  string      `orm:"-" json:"updated_at,omitempty" form:"-"`
}

func init() {
	orm.RegisterModel(new(TemplateCfg))
}

func AddTemplateCfg(m *TemplateCfg) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return id, err
}

func GetAllTemplateCfgs(query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*TemplateCfg,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(TemplateCfg))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*TemplateCfg
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

func GetTemplateCfgById(id int64) (v *TemplateCfg, err error) {
	o := models.GetDefaultDB()
	v = &TemplateCfg{TemplateCfgId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}
func GetTemplateCfgByAppIdAndType(partnerId int64,appId,titleId string) (v *TemplateCfg, err error) {
	o := models.GetDefaultDB()
	v = &TemplateCfg{PartnerId:partnerId,AppId:appId,PubTitleId:titleId}
	if err = o.Read(v,"PartnerId","AppId","PubTitleId"); err == nil {
		return v, nil
	}
	return nil, err
}
func UpdateTemplateCfgById(m *TemplateCfg,param ... string) (err error) {
	o := models.GetDefaultDB()
	v := TemplateCfg{TemplateCfgId: m.TemplateCfgId}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m, param...); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

func DeleteTemplateCfg(id int64) (err error) {
	o := models.GetDefaultDB()
	v := TemplateCfg{TemplateCfgId: id}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&v); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

func CheckTemplateExistByAppId(partnerId int64, appId string) bool {
	o := models.GetDefaultDB()
	exist := o.QueryTable(new(TemplateCfg)).Filter("partner_id", partnerId).Filter("app_id", appId).Exist()
	return exist
}

type PubTemplate struct {
	PubTitleId    string
	PubTitle      string
	KeywordIdList []int
}

//系统所需的所有公有模板
func GetAllPubTemplate() (cList map[string]*PubTemplate) {
	cList = make(map[string]*PubTemplate)
	pubTemplate := new(PubTemplate)
	pubTemplate.PubTitleId = "AT0163"
	pubTemplate.PubTitle =   "订单确认通知"
	pubTemplate.KeywordIdList = []int{1,2,4}
	cList[pubTemplate.PubTitle] = pubTemplate
    //
	pubTemplate = new(PubTemplate)
	pubTemplate.PubTitleId = "AT0007"
	pubTemplate.PubTitle =   "订单发货提醒"
	pubTemplate.KeywordIdList = []int{7,21,22,53}
	cList[pubTemplate.PubTitle] = pubTemplate
	//
	pubTemplate = new(PubTemplate)
	pubTemplate.PubTitleId = "AT0503"
	pubTemplate.PubTitle =   "订单评价提醒"
	pubTemplate.KeywordIdList = []int{1,6,2}
	cList[pubTemplate.PubTitle] = pubTemplate
	//
	pubTemplate = new(PubTemplate)
	pubTemplate.PubTitleId = "AT0104"
	pubTemplate.PubTitle =   "预约成功通知"
	pubTemplate.KeywordIdList = []int{6,7,11}
	cList[pubTemplate.PubTitle] = pubTemplate
	//
	pubTemplate = new(PubTemplate)
	pubTemplate.PubTitleId = "AT0240"
	pubTemplate.PubTitle =   "预约活动开始提醒"
	pubTemplate.KeywordIdList = []int{4,10,3,8}
	cList[pubTemplate.PubTitle] = pubTemplate
	//
	pubTemplate = new(PubTemplate)
	pubTemplate.PubTitleId = "AT0087"
	pubTemplate.PubTitle =   "订购成功通知"
	pubTemplate.KeywordIdList = []int{2,3,7}
	cList[pubTemplate.PubTitle] = pubTemplate
	//
	pubTemplate = new(PubTemplate)
	pubTemplate.PubTitleId = "AT0146"
	pubTemplate.PubTitle =   "审核结果通知"
	pubTemplate.KeywordIdList = []int{35,18,49}
	cList[pubTemplate.PubTitle] = pubTemplate
	return
}
